package com.example.rbacmanage.handler;

import com.example.rbacmanage.exception.MyException;
import com.example.rbacmanage.vo.CustomErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<Object> handleException(Exception e) {
        // 记录异常，以便调试和监控
        e.printStackTrace(); // 或者使用日志框架如logback, log4j等记录异常
        // 返回500状态码和错误信息
        CustomErrorResponse errorResponse = new CustomErrorResponse();
        errorResponse.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        errorResponse.setMessage(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    @ExceptionHandler(MyException.class)
    public ResponseEntity<CustomErrorResponse> handle(MyException ex){
        CustomErrorResponse errorResponse = new CustomErrorResponse();
        errorResponse.setCode(ex.getCode());
        errorResponse.setMessage(ex.getMessage());
        HttpStatus httpStatus;
        if (ex.getCode() == HttpStatus.UNAUTHORIZED.value()){
            httpStatus=HttpStatus.UNAUTHORIZED;
        }else  if (ex.getCode() == HttpStatus.NOT_FOUND.value()){
            httpStatus=HttpStatus.NOT_FOUND;
        }else  if (ex.getCode() == HttpStatus.BAD_REQUEST.value()){
            httpStatus=HttpStatus.BAD_REQUEST;
        }else  if (ex.getCode() == 512){
            httpStatus=HttpStatus.INTERNAL_SERVER_ERROR;
        }else{
            httpStatus=HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return new ResponseEntity<>(errorResponse, httpStatus);
    }
}
